#include "C3DTexture.h"
#include "SDL_image.h"

C3DTexture::C3DTexture(void)
{
	m_image = NULL;
}

C3DTexture::~C3DTexture(void)
{
	Delete();
}

void C3DTexture::LoadTexture( const char* filename )
{
	if(filename==NULL)
		return;

	Delete();

	GLint  nOfColors;
	GLenum texture_format;


	m_image = IMG_Load(filename);

	nOfColors = m_image->format->BytesPerPixel;
	if (nOfColors == 4)     // contains an alpha channel
	{
		texture_format = GL_RGBA;
	} else if (nOfColors == 3)     // no alpha channel
	{	
		texture_format = GL_RGB;
	}

	glGenTextures( 1, &m_handle );

	// Bind the texture object
	glBindTexture( GL_TEXTURE_2D, m_handle );

	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

	glTexImage2D( GL_TEXTURE_2D, 0, nOfColors, m_image->w, m_image->h, 0,
		texture_format, GL_UNSIGNED_BYTE, m_image->pixels );


}

void C3DTexture::Delete()
{
	if(m_image!=NULL)
	{
		SDL_FreeSurface(m_image);
		m_image = NULL;
	}
}

void C3DTexture::Bind()
{
	glBindTexture( GL_TEXTURE_2D, m_handle );
}